﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Confucius.daoImpl;
using Confucius.dao;
using Confucius.entity;
using Confucius.utils;
using DBContent.Model;
using System.IO.IsolatedStorage;

namespace Confucius.pages
{
    public partial class DownloadGamePage : PhoneApplicationPage
    {
        private GameDAO gameDao;
        public DownloadGamePage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Page_Loaded);
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            gameDao = new GameDAOImpl((Application.Current as App));
            List<GameHeader> remoteGameList = gameDao.findRemoteGames();
            RemoteGames.ItemsSource = remoteGameList;
            LocalGames.ItemsSource = remoteGameList;
        }

        private void LocalGames_Tap(object sender, GestureEventArgs e)
        {
            // Click game item
            GameHeader data = ((FrameworkElement)e.OriginalSource).DataContext as GameHeader;
            DBGame dbGame = new DBGame();
            dbGame.GameID = data.GameID;
            String status = ConfuciusDBHelper.getGameStatus(dbGame);
            if (status.Equals(Game.READY_STATUS))
            {
                gameDao.populdateGame(data.GameID);
                gameDao.updateGameStatus(data.GameID, Game.START_STATUS);
            }
            // Store game ID
            IsolatedStorageSettings.ApplicationSettings.Remove(Constants.CURRENT_GAMEID);
            IsolatedStorageSettings.ApplicationSettings.Add(Constants.CURRENT_GAMEID, data.GameID);
            IsolatedStorageSettings.ApplicationSettings.Save();

            NavigationService.Navigate(new Uri("/pages/GamePlayPage.xaml?currentGameID=" + data.GameID, UriKind.Relative));

        }
    }
}